package top.xiaoshuaila.searescue.serialport.utils;

import sun.misc.LRUCache;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Arrays;
import java.util.Locale;

/**
 * Byte转换工具
 * 
 * @author yangle
 */
public class ByteUtils {

	/**
	 * 十六进制字符串转byte[]
	 *
	 * @param hex
	 *            十六进制字符串
	 * @return byte[]
	 */
	public static byte[] hexStr2Byte(String hex) {
		hex=hex.replaceAll(" ","");
		if (hex == null) {
			return new byte[] {};
		}
		// 奇数位补0
		if (hex.length() % 2 != 0) {
			hex = "0" + hex;
		}
		int length = hex.length();
		ByteBuffer buffer = ByteBuffer.allocate(length / 2);
		for (int i = 0; i < length; i++) {
			String hexStr = hex.charAt(i) + "";
			i++;
			hexStr += hex.charAt(i);
			byte b = (byte) Integer.parseInt(hexStr, 16);
			buffer.put(b);
		}
		return buffer.array();
	}
	/**
	 * 十六进制字符串转int[]
	 *
	 * @param hex
	 *            十六进制字符串
	 * @return int[]
	 */
	public static int[] hexStr2Int(String hex) {
		if (hex == null) {
			return new int[] {};
		}
		// 奇数位补0
		if (hex.length() % 2 != 0) {
			hex = "0" + hex;
		}
		int length = hex.length();
		IntBuffer buffer = IntBuffer.allocate(length / 2);
		for (int i = 0; i < length; i++) {
			String hexStr = hex.charAt(i) + "";
			i++;
			hexStr += hex.charAt(i);
			int b = Integer.parseInt(hexStr, 16);
			buffer.put(b);
		}
		return buffer.array();
	}

	/**
	 * byte[]转十六进制字符串
	 * 
	 * @param array
	 *            byte[]
	 * @return 十六进制字符串
	 */
	public static String byteArrayToHexString(byte[] array) {
		if (array == null) {
			return "";
		}
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < array.length; i++) {
			buffer.append(byteToHex(array[i]));
		}
		return buffer.toString();
	}

	/**
	 * byte转十六进制字符
	 * 
	 * @param b
	 *            byte
	 * @return 十六进制字符
	 */
	public static String byteToHex(byte b) {
		String hex = Integer.toHexString(b & 0xFF);
		if (hex.length() == 1) {
			hex = '0' + hex;
		}
		return hex.toUpperCase(Locale.getDefault());
	}
	/*
	* byte转字符串*/
	public static String ByteToString(byte[]bytes){
		StringBuilder str=new StringBuilder();
		for(int i=0;i<bytes.length;i++)
			str.append((char)(bytes[i]));
		return str.toString();
	}
	/*生成lrc校验码*/
	public static String LRC(String str){
		byte[]m=ByteUtils.hexStr2Byte(str);
		int x=0;
		int l=m.length;
		for(int i=0;i<l;i++){
			x=x+m[i];
		}
		x=~x;
		int d= (x&(0xff));
		d+=1;
		return Integer.toHexString(d);
	}
}
